package view.admin;

import controller.SeatController;
import model.Seat;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 添加楼层对话框
 */
public class FloorAddDialog extends JDialog {
    private SeatController seatController;
    private boolean confirmed = false;

    private JComboBox<String> areaTypeComboBox;
    private JSpinner floorSpinner;
    private JSpinner roomCountSpinner;
    private JTextField areaNameField;
    private JComboBox<String> equipmentLevelComboBox;
    private JCheckBox hasComputerCheckBox;
    private JCheckBox hasPowerSocketCheckBox;

    private JLabel previewSeatCountLabel;

    private JButton saveButton;
    private JButton cancelButton;

    public FloorAddDialog(JFrame parent) {
        super(parent, "添加楼层", true);
        this.seatController = new SeatController();

        initComponents();
        setupLayout();
        setupEventListeners();
    }

    private void initComponents() {
        setSize(750, 600);
        setLocationRelativeTo(getParent());
        setResizable(false);

        // 现代化窗口样式
        setUndecorated(false);

        // 区域类型选择
        areaTypeComboBox = new JComboBox<>();
        areaTypeComboBox.addItem("宿舍区自习室");
        areaTypeComboBox.addItem("图书馆");
        areaTypeComboBox.addItem("教学楼自习室");
        areaTypeComboBox.addItem("其他区域");
        styleComboBox(areaTypeComboBox);

        // 楼层选择
        floorSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 20, 1));
        styleSpinner(floorSpinner);

        // 房间数量选择
        roomCountSpinner = new JSpinner(new SpinnerNumberModel(6, 1, 10, 1));
        styleSpinner(roomCountSpinner);

        // 监听房间数量变化以更新座位总数显示
        roomCountSpinner.addChangeListener(e -> updateSeatCountPreview());

        // 区域名称
        areaNameField = new JTextField(20);
        areaNameField.setText("新区域");
        styleTextField(areaNameField);

        // 设备等级
        equipmentLevelComboBox = new JComboBox<>();
        equipmentLevelComboBox.addItem("基础设备");
        equipmentLevelComboBox.addItem("标准设备");
        equipmentLevelComboBox.addItem("高级设备");
        styleComboBox(equipmentLevelComboBox);

        // 设备选项
        hasComputerCheckBox = new JCheckBox("配备电脑");
        hasPowerSocketCheckBox = new JCheckBox("配备电源插座");
        hasPowerSocketCheckBox.setSelected(true); // 默认选中
        styleCheckBox(hasComputerCheckBox);
        styleCheckBox(hasPowerSocketCheckBox);

        saveButton = new JButton("创建楼层");
        cancelButton = new JButton("取消");

        // 美化按钮
        styleButton(saveButton, new Color(34, 197, 94));
        styleButton(cancelButton, new Color(156, 163, 175));

        // 区域类型变化时自动更新区域名称
        areaTypeComboBox.addActionListener(e -> updateAreaNameSuggestion());
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 创建渐变背景主面板
        JPanel mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建渐变背景
                GradientPaint gradient = new GradientPaint(
                        0, 0, new Color(247, 250, 255),
                        0, getHeight(), new Color(237, 242, 255));
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 现代化标题面板
        JPanel titlePanel = createTitlePanel();
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建内容面板 - 使用左右分栏布局
        JPanel contentPanel = new JPanel(new BorderLayout(20, 0));
        contentPanel.setOpaque(false);

        // 左侧面板 - 基本信息和设备配置
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setOpaque(false);

        // 基本信息面板 - 使用更紧凑的网格布局
        JPanel basicPanel = createCompactSectionPanel("基本信息", Color.decode("#3B82F6"));
        JPanel basicContent = new JPanel(new GridBagLayout());
        basicContent.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 0, 8, 15);

        // 第一行：区域类型和楼层编号
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        basicContent.add(createStyledLabel("区域类型:", Font.BOLD), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        basicContent.add(areaTypeComboBox, gbc);

        gbc.gridx = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        basicContent.add(createStyledLabel("楼层编号:", Font.BOLD), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.5;
        basicContent.add(floorSpinner, gbc);

        // 第二行：区域名称
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        basicContent.add(createStyledLabel("区域名称:", Font.BOLD), gbc);
        gbc.gridx = 1;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        basicContent.add(areaNameField, gbc);

        // 第三行：房间数量
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        basicContent.add(createStyledLabel("房间数量:", Font.BOLD), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.5;
        basicContent.add(roomCountSpinner, gbc);

        basicPanel.add(basicContent);
        leftPanel.add(basicPanel);
        leftPanel.add(Box.createVerticalStrut(15));

        // 设备配置面板 - 更紧凑的布局
        JPanel equipmentPanel = createCompactSectionPanel("设备配置", Color.decode("#10B981"));
        JPanel equipContent = new JPanel(new GridBagLayout());
        equipContent.setOpaque(false);

        // 设备等级
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        equipContent.add(createStyledLabel("设备等级:", Font.BOLD), gbc);
        gbc.gridx = 1;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        equipContent.add(equipmentLevelComboBox, gbc);

        // 设备选项
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        equipContent.add(createStyledLabel("设备选项:", Font.BOLD), gbc);

        JPanel checkboxPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        checkboxPanel.setOpaque(false);
        checkboxPanel.add(hasComputerCheckBox);
        checkboxPanel.add(Box.createHorizontalStrut(20));
        checkboxPanel.add(hasPowerSocketCheckBox);
        gbc.gridx = 1;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        equipContent.add(checkboxPanel, gbc);

        equipmentPanel.add(equipContent);
        leftPanel.add(equipmentPanel);

        // 右侧面板 - 预览信息
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setOpaque(false);

        JPanel previewPanel = createEnhancedPreviewPanel();
        rightPanel.add(previewPanel);

        // 添加左右面板到内容面板
        contentPanel.add(leftPanel, BorderLayout.CENTER);
        contentPanel.add(rightPanel, BorderLayout.EAST);

        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.setOpaque(false);
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel, BorderLayout.CENTER);
    }

    /**
     * 创建标题面板
     */
    private JPanel createTitlePanel() {
        JPanel titlePanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建圆角背景
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);

                // 添加阴影效果
                g2d.setColor(new Color(0, 0, 0, 10));
                g2d.fillRoundRect(2, 2, getWidth(), getHeight(), 15, 15);
            }
        };
        titlePanel.setOpaque(false);
        titlePanel.setLayout(new BorderLayout());
        titlePanel.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));

        JLabel titleLabel = new JLabel("添加新楼层", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel subtitleLabel = new JLabel("快速创建整个楼层的座位布局", JLabel.CENTER);
        subtitleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        subtitleLabel.setForeground(new Color(107, 114, 128));

        titlePanel.add(titleLabel, BorderLayout.CENTER);
        titlePanel.add(subtitleLabel, BorderLayout.SOUTH);

        return titlePanel;
    }

    /**
     * 创建紧凑的section面板
     */
    private JPanel createCompactSectionPanel(String title, Color accentColor) {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建白色圆角背景
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 12, 12);

                // 添加微妙的阴影
                g2d.setColor(new Color(0, 0, 0, 5));
                g2d.fillRoundRect(1, 1, getWidth(), getHeight(), 12, 12);

                // 顶部彩色条纹
                g2d.setColor(accentColor);
                g2d.fillRoundRect(0, 0, getWidth(), 4, 12, 12);
            }
        };

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 创建标题面板
        JPanel titleContainer = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        titleContainer.setOpaque(false);

        JLabel iconLabel = new JLabel("●");
        iconLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        iconLabel.setForeground(accentColor);
        iconLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 6));

        JLabel sectionTitle = new JLabel(title);
        sectionTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        sectionTitle.setForeground(new Color(30, 41, 59));

        titleContainer.add(iconLabel);
        titleContainer.add(sectionTitle);
        titleContainer.setAlignmentX(Component.LEFT_ALIGNMENT);

        panel.add(titleContainer);
        panel.add(Box.createVerticalStrut(12));

        return panel;
    }

    /**
     * 创建样式化标签
     */
    private JLabel createStyledLabel(String text, int fontStyle) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", fontStyle, 13));
        label.setForeground(new Color(55, 65, 81));
        return label;
    }

    /**
     * 创建增强的预览面板
     */
    private JPanel createEnhancedPreviewPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建渐变背景
                GradientPaint gradient = new GradientPaint(
                        0, 0, new Color(168, 85, 247, 10),
                        0, getHeight(), new Color(168, 85, 247, 30));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 12, 12);

                // 边框
                g2d.setColor(new Color(168, 85, 247, 100));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 12, 12);
            }
        };

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setPreferredSize(new Dimension(280, 350));

        // 标题
        JLabel titleLabel = new JLabel("创建预览", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(168, 85, 247));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(titleLabel);
        panel.add(Box.createVerticalStrut(15));

        // 座位数量预览
        previewSeatCountLabel = new JLabel("将创建 48 个座位", JLabel.CENTER);
        previewSeatCountLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        previewSeatCountLabel.setForeground(new Color(30, 41, 59));
        previewSeatCountLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(previewSeatCountLabel);
        panel.add(Box.createVerticalStrut(8));

        // 详细说明
        JLabel previewDetailLabel = new JLabel("6 个房间 × 8 个座位/房间", JLabel.CENTER);
        previewDetailLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        previewDetailLabel.setForeground(new Color(107, 114, 128));
        previewDetailLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(previewDetailLabel);
        panel.add(Box.createVerticalStrut(20));

        // 创建一个小的座位布局预览图
        JPanel layoutPreview = createSeatLayoutPreview();
        panel.add(layoutPreview);

        panel.add(Box.createVerticalStrut(15));

        // 说明文字
        JLabel noteLabel = new JLabel(
                "<html><div style='text-align: center;'>座位编号格式：楼层-房间-座位<br/>例如：1-01-01, 1-01-02...</div></html>");
        noteLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        noteLabel.setForeground(new Color(107, 114, 128));
        noteLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(noteLabel);

        return panel;
    }

    /**
     * 创建座位布局预览图
     */
    private JPanel createSeatLayoutPreview() {
        JPanel layoutPanel = new JPanel(new GridLayout(2, 4, 3, 3));
        layoutPanel.setOpaque(false);
        layoutPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(168, 85, 247, 100)),
                "房间布局示例",
                0,
                0,
                new Font("Microsoft YaHei", Font.PLAIN, 10),
                new Color(107, 114, 128)));

        // 创建8个小方块代表座位
        for (int i = 1; i <= 8; i++) {
            JLabel seatLabel = new JLabel(String.valueOf(i), JLabel.CENTER);
            seatLabel.setPreferredSize(new Dimension(25, 25));
            seatLabel.setOpaque(true);
            seatLabel.setBackground(new Color(59, 130, 246, 100));
            seatLabel.setBorder(BorderFactory.createLineBorder(new Color(59, 130, 246, 150), 1));
            seatLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 10));
            seatLabel.setForeground(new Color(30, 64, 175));
            layoutPanel.add(seatLabel);
        }

        return layoutPanel;
    }

    private JPanel createSectionPanel(String title, Color accentColor) {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建白色圆角背景
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 12, 12);

                // 添加微妙的阴影
                g2d.setColor(new Color(0, 0, 0, 5));
                g2d.fillRoundRect(1, 1, getWidth(), getHeight(), 12, 12);

                // 顶部彩色条纹
                g2d.setColor(accentColor);
                g2d.fillRoundRect(0, 0, getWidth(), 4, 12, 12);
            }
        };

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titleContainer = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        titleContainer.setOpaque(false);

        JLabel iconLabel = new JLabel("●");
        iconLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        iconLabel.setForeground(accentColor);
        iconLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 8));

        JLabel sectionTitle = new JLabel(title);
        sectionTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        sectionTitle.setForeground(new Color(30, 41, 59));

        titleContainer.add(iconLabel);
        titleContainer.add(sectionTitle);
        titleContainer.setAlignmentX(Component.LEFT_ALIGNMENT);

        panel.add(titleContainer);
        panel.add(Box.createVerticalStrut(15));

        return panel;
    }

    private JPanel createFormRow(String label, JComponent component) {
        JPanel row = new JPanel(new BorderLayout(15, 0));
        row.setOpaque(false);
        row.setBorder(BorderFactory.createEmptyBorder(8, 0, 8, 0));

        JLabel labelComponent = new JLabel(label);
        labelComponent.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        labelComponent.setForeground(new Color(55, 65, 81));
        labelComponent.setPreferredSize(new Dimension(100, 35));
        labelComponent.setVerticalAlignment(JLabel.CENTER);

        row.add(labelComponent, BorderLayout.WEST);
        row.add(component, BorderLayout.CENTER);

        return row;
    }

    private void styleButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(130, 42));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 设置圆角和阴影效果
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);

        // 重写按钮绘制以添加圆角和阴影
        button.setUI(new javax.swing.plaf.basic.BasicButtonUI() {
            @Override
            public void paint(Graphics g, JComponent c) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                AbstractButton b = (AbstractButton) c;

                // 绘制阴影
                g2d.setColor(new Color(0, 0, 0, 20));
                g2d.fillRoundRect(2, 2, c.getWidth(), c.getHeight(), 12, 12);

                // 绘制按钮背景
                if (b.getModel().isPressed()) {
                    g2d.setColor(backgroundColor.darker().darker());
                } else if (b.getModel().isRollover()) {
                    g2d.setColor(backgroundColor.brighter());
                } else {
                    g2d.setColor(backgroundColor);
                }
                g2d.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 12, 12);

                g2d.dispose();
                super.paint(g, c);
            }
        });
    }

    private void setupEventListeners() {
        saveButton.addActionListener(e -> handleSave());
        cancelButton.addActionListener(e -> dispose());
    }

    private void updateAreaNameSuggestion() {
        String areaType = (String) areaTypeComboBox.getSelectedItem();
        int floor = (Integer) floorSpinner.getValue();

        String suggestion;
        switch (areaType) {
            case "宿舍区自习室":
                suggestion = floor + "楼宿舍自习室";
                break;
            case "图书馆":
                suggestion = "图书馆" + floor + "层";
                break;
            case "教学楼自习室":
                suggestion = "第" + floor + "教学楼自习室";
                break;
            case "其他区域":
                suggestion = floor + "楼其他区域";
                break;
            default:
                suggestion = floor + "楼新区域";
                break;
        }
        areaNameField.setText(suggestion);
    }

    private void handleSave() {
        // 验证输入
        String areaName = areaNameField.getText().trim();
        if (areaName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写区域名称!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int floor = (Integer) floorSpinner.getValue();
        int roomCount = (Integer) roomCountSpinner.getValue();

        // 检查楼层是否已存在座位
        try {
            if (seatController.checkFloorExists(floor)) {
                int option = JOptionPane.showConfirmDialog(this,
                        "检测到楼层 " + floor + " 已有座位存在！\n" +
                                "是否要继续添加新座位？\n\n" +
                                "注意：这可能会导致座位号冲突。",
                        "楼层冲突警告",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE);

                if (option != JOptionPane.YES_OPTION) {
                    return;
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "检查楼层状态失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确认对话框
        String message = String.format(
                "确认要创建以下楼层吗？\n\n" +
                        "区域名称: %s\n" +
                        "楼层编号: %d\n" +
                        "房间数量: %d\n" +
                        "总座位数: %d (每房间8个座位)\n\n" +
                        "此操作将自动创建所有座位，如有重复将跳过。",
                areaName, floor, roomCount, roomCount * 8);

        int result = JOptionPane.showConfirmDialog(this, message, "确认创建",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (result != JOptionPane.YES_OPTION) {
            return;
        }

        try {
            // 生成所有座位
            List<Seat> seats = generateSeats(floor, roomCount, areaName);

            // 批量添加座位，允许部分失败
            int createdCount = 0;
            int skippedCount = 0;
            StringBuilder errorDetails = new StringBuilder();

            for (Seat seat : seats) {
                try {
                    if (seatController.addSeat(seat)) {
                        createdCount++;
                    } else {
                        skippedCount++;
                    }
                } catch (Exception e) {
                    skippedCount++;
                    if (e.getMessage().contains("Duplicate") || e.getMessage().contains("unique_position")) {
                        // 座位已存在，跳过
                        continue;
                    } else {
                        // 其他错误，记录详情
                        if (errorDetails.length() < 200) { // 限制错误信息长度
                            errorDetails.append("座位 ").append(seat.getSeatNumber())
                                    .append(": ").append(e.getMessage()).append("\n");
                        }
                    }
                }
            }

            // 显示结果
            if (createdCount > 0) {
                confirmed = true;
                String resultMessage = String.format("楼层创建完成！\n" +
                        "成功创建: %d 个座位\n" +
                        "跳过/重复: %d 个座位", createdCount, skippedCount);

                if (errorDetails.length() > 0) {
                    resultMessage += "\n\n部分座位创建时遇到问题:\n" + errorDetails.toString();
                }

                JOptionPane.showMessageDialog(this, resultMessage, "创建完成", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this,
                        "没有创建任何新座位！\n" +
                                "可能原因：\n" +
                                "1. 该楼层的所有座位都已存在\n" +
                                "2. 座位编号冲突\n\n" +
                                "跳过的座位数: " + skippedCount +
                                (errorDetails.length() > 0 ? "\n\n错误详情:\n" + errorDetails.toString() : ""),
                        "创建失败", JOptionPane.WARNING_MESSAGE);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "创建失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    private List<Seat> generateSeats(int floor, int roomCount, String areaName) {
        List<Seat> seats = new ArrayList<>();

        String equipment = getEquipmentDescription();
        boolean hasComputer = hasComputerCheckBox.isSelected();
        boolean hasPowerSocket = hasPowerSocketCheckBox.isSelected();

        // 为每个房间生成8个座位
        for (int room = 1; room <= roomCount; room++) {
            for (int seatIndex = 1; seatIndex <= 8; seatIndex++) {
                Seat seat = new Seat();

                // 设置座位信息
                seat.setFloor(floor);
                seat.setRoom(room);
                seat.setSeatIndex(seatIndex);
                seat.setArea(areaName);
                seat.setSeatNumber(generateSeatNumber(floor, room, seatIndex));
                seat.setStatus(0); // 默认可用
                seat.setEquipment(equipment);
                seat.setHasComputer(hasComputer);
                seat.setHasPowerSocket(hasPowerSocket);

                seats.add(seat);
            }
        }

        return seats;
    }

    private String generateSeatNumber(int floor, int room, int seatIndex) {
        return String.format("%d-%d-%02d", floor, room, seatIndex);
    }

    private String getEquipmentDescription() {
        String level = (String) equipmentLevelComboBox.getSelectedItem();
        StringBuilder desc = new StringBuilder();

        switch (level) {
            case "基础设备":
                desc.append("桌椅");
                break;
            case "标准设备":
                desc.append("桌椅、台灯");
                break;
            case "高级设备":
                desc.append("桌椅、台灯、储物柜");
                break;
        }

        if (hasComputerCheckBox.isSelected()) {
            desc.append("、电脑");
        }
        if (hasPowerSocketCheckBox.isSelected()) {
            desc.append("、电源插座");
        }

        return desc.toString();
    }

    /**
     * 美化组合框样式
     */
    private void styleComboBox(JComboBox<String> comboBox) {
        comboBox.setPreferredSize(new Dimension(180, 32));
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        comboBox.setBackground(Color.WHITE);
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
        comboBox.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加焦点效果
        comboBox.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                comboBox.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(59, 130, 246), 2),
                        BorderFactory.createEmptyBorder(4, 9, 4, 9)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                comboBox.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(5, 10, 5, 10)));
            }
        });
    }

    /**
     * 美化Spinner样式
     */
    private void styleSpinner(JSpinner spinner) {
        spinner.setPreferredSize(new Dimension(100, 32));
        spinner.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));

        // 美化编辑器
        JComponent editor = spinner.getEditor();
        if (editor instanceof JSpinner.DefaultEditor) {
            JTextField textField = ((JSpinner.DefaultEditor) editor).getTextField();
            textField.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
            textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        }

        spinner.setBorder(BorderFactory.createLineBorder(new Color(209, 213, 219), 1));
    }

    /**
     * 美化文本框样式
     */
    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(180, 32));
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));

        // 添加焦点效果
        textField.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(59, 130, 246), 2),
                        BorderFactory.createEmptyBorder(7, 11, 7, 11)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            }
        });
    }

    /**
     * 美化复选框样式
     */
    private void styleCheckBox(JCheckBox checkBox) {
        checkBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        checkBox.setForeground(new Color(55, 65, 81));
        checkBox.setOpaque(false);
        checkBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
        checkBox.setFocusPainted(false);

        // 添加悬停效果
        checkBox.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                checkBox.setForeground(new Color(59, 130, 246));
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                checkBox.setForeground(new Color(55, 65, 81));
            }
        });
    }

    /**
     * 创建预览面板
     */
    private JPanel createPreviewPanel() {
        JPanel panel = createSectionPanel("创建预览", new Color(168, 85, 247));

        previewSeatCountLabel = new JLabel("将创建 48 个座位");
        previewSeatCountLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        previewSeatCountLabel.setForeground(new Color(30, 41, 59));
        previewSeatCountLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel previewDetailLabel = new JLabel("6 个房间 × 8 个座位/房间 = 48 个座位");
        previewDetailLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        previewDetailLabel.setForeground(new Color(107, 114, 128));
        previewDetailLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setOpaque(false);

        contentPanel.add(previewSeatCountLabel);
        contentPanel.add(Box.createVerticalStrut(5));
        contentPanel.add(previewDetailLabel);

        panel.add(contentPanel);

        return panel;
    }

    /**
     * 更新座位数量预览
     */
    private void updateSeatCountPreview() {
        int roomCount = (Integer) roomCountSpinner.getValue();
        int totalSeats = roomCount * 8;

        if (previewSeatCountLabel != null) {
            previewSeatCountLabel.setText("将创建 " + totalSeats + " 个座位");

            // 更新详细说明 - 寻找预览详情标签
            Container parent = previewSeatCountLabel.getParent();
            if (parent != null) {
                Component[] components = parent.getComponents();
                // 查找详细说明标签（通常在座位数量标签之后）
                boolean foundCountLabel = false;
                for (Component component : components) {
                    if (foundCountLabel && component instanceof JLabel) {
                        JLabel detailLabel = (JLabel) component;
                        if (detailLabel.getText().contains("个房间")) {
                            detailLabel.setText(roomCount + " 个房间 × 8 个座位/房间");
                            break;
                        }
                    }
                    if (component == previewSeatCountLabel) {
                        foundCountLabel = true;
                    }
                }
            }
        }
    }

    public boolean isConfirmed() {
        return confirmed;
    }
}
